#include  "msp430g2553.h"
#define Bitime 13*4					// 0x0D

char waitForButton = 1;

void init_uart(void);
void transmit_uart(char data);

void main(void) {
	init_uart();
  // Configure Push Button (input on P1.3)
  P1DIR &= ~BIT3;
  P1OUT |= BIT3;								// Enable pull-up
  P1REN |= BIT3;								//   resistor...
  P1IES |= BIT3;								// Want an interrupt when P1.3 goes low...
  P1IFG &= ~BIT3;
  P1IE |= BIT3;
  // Ensure that the LED on P1.6 is off:
  P1DIR |= BIT6;
  P1OUT &= ~BIT6;
  // Initial loop:  wait for a button press
  while (waitForButton)
   	__bis_SR_register(CPUOFF + GIE);        // LPM0 with interrupts enabled
  // Transmit!
  transmit_uart(0x01);
//  // Illuminate LED and halt
  P1OUT |= BIT6;
  _delay_cycles(3000000);
  P1OUT &=~ BIT6;
  while (1){
	  transmit_uart(0x02);
	P1DIR |= BIT0;
  	P1OUT |= BIT0; _delay_cycles(1000000);
  	P1OUT &= ~BIT0; _delay_cycles(1000000);
  	  	   }
  }
// ISR for changes on port 1.  Used while we're waiting for the initial button press
#pragma vector=PORT1_VECTOR
__interrupt void PORT1_ISR(void) {
  if (P1IFG & BIT3)
	  waitForButton = 0,					// Got our button press!
	  P1IE &= ~BIT3;
  P1IFG = 0;
  __bic_SR_register_on_exit(LPM3_bits);			// Resume main() on return
  }
void init_uart(void)
{
	WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
	  // Setup clock
	  BCSCTL1 = CALBC1_1MHZ;                    // Initialize DCOCLK (1 MHz)
	  DCOCTL = CALDCO_1MHZ;
	  BCSCTL2 &= ~(DIVS_3);                     // SMCLK = DCO = 1MHz
	  // Setup USCI for 115200 baud UART
	  P1SEL = BIT1 + BIT2;                      // P1.1 = RXD, P1.2=TXD
	  P1SEL2 = BIT1 + BIT2;
	  UCA0CTL1 |= UCSSEL_2;                     // SMCLK
	  UCA0BR0 = 8;                              // 1MHz 115200
	  UCA0BR1 = 0;                              // 1MHz 115200
	  UCA0MCTL = UCBRS_5;               		// Modulation UCBRSx = 5
	  UCA0CTL1 &= ~UCSWRST;                     // **Initialize USCI state machine**
}
void transmit_uart(char data)
{
	// dung polling nen k can enable ngat khi truyen xong
	while(!(IFG2 & UCA0TXIFG)) {};
	  UCA0TXBUF = data;
	  while(!(IFG2 & UCA0TXIFG)){				// neu chua gui dc tiep tuc gui lai
		  	  	  	  	  	  	  UCA0TXBUF = data;
	  	  	  	  	  	  	    }
}
